package com.cloud.core.httpclient;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;

import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.codehaus.jackson.node.ObjectNode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

/**
 * 1Cloud1
 * @author Administrator
 * @since 2015-11-13
 * @version 1.0 
 */
@Component("HttpClientProxy")
public class HttpClientProxy {
	@Value("${org_name}")
	public String org_name;
	@Value("${app_name}")
	public String app_name;
	@Value("${api_server_host}")
	public String api_server_host;
	@Value("${appkey}")
	public String appkey;
	@Value("${app_client_id}")
	public String app_client_id;
	@Value("${app_client_secret}")
	public String app_client_secret;
	
	/**
	 * Get请求
	 * @param uri
	 * @param header
	 * @return
	 */
	public String getStringObjectFromGet(String uri, Header header) {
		CloseableHttpClient httpclient = createSSLClientDefault();
		HttpGet get = new HttpGet(uri);
		get.setHeader("Content-Type", "application/json");
		if(header != null)
			get.addHeader(header);
		CloseableHttpResponse response = null;
		try {
			response = httpclient.execute(get);
			String result = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
			return result;
		} catch (ClientProtocolException e) {
			return null;
		} catch (IOException e) {
			return null;
		} finally {
			IOUtils.closeQuietly(response);
			IOUtils.closeQuietly(httpclient);
		}
	}
	
	/**
	 * Get请求
	 * @param uri
	 * @param header
	 * @return
	 */
	public JsonObject getJsonObjectFromGet(String uri, Header header) {
		CloseableHttpClient httpclient = createSSLClientDefault();
		HttpGet get = new HttpGet(uri);
		get.setHeader("Content-Type", "application/json");
		if(header != null)
			get.addHeader(header);
		CloseableHttpResponse response = null;
		try {
			response = httpclient.execute(get);
			String result = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
			JsonParser jsonParser = new JsonParser();
			JsonObject jso = jsonParser.parse(result).getAsJsonObject();
			return jso;
		} catch (ClientProtocolException e) {
			return null;
		} catch (IOException e) {
			return null;
		} finally {
			IOUtils.closeQuietly(response);
			IOUtils.closeQuietly(httpclient);
		}
	}

	/**
	 * Post请求
	 * @param uri
	 * @param dataNode
	 * @param header
	 * @return
	 */
	public JsonObject getJsonObjectFromPost(String uri, ObjectNode dataNode, Header header) {
		CloseableHttpClient httpclient = createSSLClientDefault();
		CloseableHttpResponse response = null;
		try {
			StringEntity entity = new StringEntity(dataNode.toString(), "UTF-8");
			HttpPost post = new HttpPost(uri);
			post.setHeader("Content-Type", "application/json");
			if(header != null)
				post.addHeader(header);
			post.setEntity(entity);
			response = httpclient.execute(post);
			String result = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
			JsonParser jsonParser = new JsonParser();
			JsonObject jso = jsonParser.parse(result).getAsJsonObject();
			return jso;
		} catch (ClientProtocolException e) {
			return null;
		} catch (IOException e) {
			return null;
		} finally {
			IOUtils.closeQuietly(response);
			IOUtils.closeQuietly(httpclient);
		}
	}
	
	public JsonObject getJsonObjectFromPut(String uri, ObjectNode dataNode, Header header) {
		CloseableHttpClient httpclient = createSSLClientDefault();
		CloseableHttpResponse response = null;
		try {
			StringEntity entity = new StringEntity(dataNode.toString(), "UTF-8");
			HttpPut put = new HttpPut(uri);
			put.setHeader("Content-Type", "application/json");
			if(header != null)
				put.addHeader(header);
			put.setEntity(entity);
			response = httpclient.execute(put);
			String result = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
			JsonParser jsonParser = new JsonParser();
			JsonObject jso = jsonParser.parse(result).getAsJsonObject();
			return jso;
		} catch (ClientProtocolException e) {
			return null;
		} catch (IOException e) {
			return null;
		} finally {
			IOUtils.closeQuietly(response);
			IOUtils.closeQuietly(httpclient);
		}
	}
	
	public JsonObject getJsonObjectFromDelete(String uri, ObjectNode dataNode, Header header) {
		CloseableHttpClient httpclient = createSSLClientDefault();
		CloseableHttpResponse response = null;
		try {
			HttpDelete delete = new HttpDelete(uri);
			delete.setHeader("Content-Type", "application/json");
			if(header != null)
				delete.addHeader(header);
			response = httpclient.execute(delete);
			String result = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
			JsonParser jsonParser = new JsonParser();
			JsonObject jso = jsonParser.parse(result).getAsJsonObject();
			return jso;
		} catch (ClientProtocolException e) {
			return null;
		} catch (IOException e) {
			return null;
		} finally {
			IOUtils.closeQuietly(response);
			IOUtils.closeQuietly(httpclient);
		}
	}

	private CloseableHttpClient createSSLClientDefault() {
		try {
			SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
				public boolean isTrusted(X509Certificate[] chain,
				String authType) throws CertificateException {
					return true;
				}
			}).build();
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
			return HttpClients.custom().setSSLSocketFactory(sslsf).build();
		} catch (KeyManagementException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (KeyStoreException e) {
			e.printStackTrace();
		}
		return HttpClients.createDefault();
	}

	public String getOrg_name() {
		return org_name;
	}

	public void setOrg_name(String org_name) {
		this.org_name = org_name;
	}

	public String getApp_name() {
		return app_name;
	}

	public void setApp_name(String app_name) {
		this.app_name = app_name;
	}

	public String getApi_server_host() {
		return api_server_host;
	}

	public void setApi_server_host(String api_server_host) {
		this.api_server_host = api_server_host;
	}

	public String getAppkey() {
		return appkey;
	}

	public void setAppkey(String appkey) {
		this.appkey = appkey;
	}

	public String getApp_client_id() {
		return app_client_id;
	}

	public void setApp_client_id(String app_client_id) {
		this.app_client_id = app_client_id;
	}

	public String getApp_client_secret() {
		return app_client_secret;
	}

	public void setApp_client_secret(String app_client_secret) {
		this.app_client_secret = app_client_secret;
	}
	
	public static void main(String[] args) {
		JsonParser jsonParser = new JsonParser();
		String result = "{\"action\" : \"post\",\"application\" : \"a2e433a0-ab1a-11e2-a134-85fca932f094\",\"params\" : { },\"path\" : \"/users\",\"uri\" : \"https://a1.easemob.com/easemob-demo/chatdemoui/users\",\"entities\" : [ {	\"uuid\" : \"7f90f7ca-bb24-11e2-b2d0-6d8e359945e4\",	\"type\" : \"user\",	\"created\" : 1368377620796,	\"modified\" : 1368377620796,	\"username\" : \"jliu\",	\"activated\" : true} ],\"timestamp\" : 1368377620793,\"duration\" : 125,\"organization\" : \"easemob-demo\",\"applicationName\" : \"chatdemo\"}";
		JsonObject jso = jsonParser.parse(result).getAsJsonObject();
		System.out.println(jso.has("action")+"===="+jso.toString().contains("activated"));
	}
}
